from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
import datetime
import time

# 定义初始化IP池
ip_pool = {}
# 定义超时时间（s）
OUT_TIME = 1
# 访问频率
FREQUENCY = 10


class Throttle(MiddlewareMixin):
    def process_request(self, request):
        # 获取IP
        ip = request.META.get('REMOTE_ADDR')
        # 获取当前访问时间戳
        timer = time.time()

        # 如果IP池不存在该IP, 则初始化该IP到IP池
        if not ip_pool.get(ip):
            ip_pool[ip] = []

        history = ip_pool[ip]

        # 剔除n时间之外的数据，只记录OUT_TIME内时间戳
        while history and timer - history[-1] > OUT_TIME:
            history.pop()

        # 判断频率
        if len(history) > FREQUENCY:
            return HttpResponse('访问频率太快')

        # 插入当前时间戳
        history.insert(0, timer)
        return
